<template>
    <div class="shop">
        <div class="top">
            <h2>购物车</h2>
            <div class="btn">
                <van-button v-for="tab in tabs" :key="tab.name" :class="{ active: activeTab === tab.name }"
                    @click="toggleButton(tab.name)">
                    {{ tab.name }}
                </van-button>
            </div>
        </div>
        <div class="middle">
            <van-checkbox-group v-model="checked" ref="checkboxGroup" @change="changeCheckboxGroup">
                <van-checkbox label-disabled :name="item.id" v-for="item in dataList" :key="item.id">
                    <van-swipe-cell>
                        <van-card :price="item.price" :desc="'规格:' + item.attrs.join()" :title="item.lists.name"
                            :thumb="item.lists.image">
                            <template #num>
                                <van-stepper @change="changeStep($event, item)" :name="item.id" v-model="item.number"
                                    theme="round" button-size="22" disable-input />
                            </template>
                        </van-card>
                        <template #right>
                            <van-button square @click="deleteButton(item.id)" style="height: 100%;" text="删除"
                                type="danger" class="delete-button" />
                        </template>
                    </van-swipe-cell>
                </van-checkbox>
            </van-checkbox-group>
        </div>
        <div class="btm">
            <van-submit-bar button-color="#0A81F9" :price="computedTotalPrice * 100" button-text="去结算"
                @submit="onSubmit">
                <van-checkbox v-model="check" label-disabled @click="toggleAllCheckboxes">全选</van-checkbox>
            </van-submit-bar>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { Toast } from 'vant';
import { useRouter } from "vue-router";
import { ProductcartLists, ProductcartDel, preOrder } from '../../api/index';

const dataList = ref([]);
const totalPrice = ref(0);
const check = ref(false);
const checked = ref([]);
const checkboxGroup = ref(null);
const router = useRouter();

const activeTab = ref('商城商品'); // 默认激活的 Tab

const tabs = ref([
    { name: '商城商品', type: 'shop' },
    { name: '消费商品', type: 'bill' },
]);
const findReamrkByName = (actions, name) => {
    const action = actions.find(item => item.name === name);
    return action ? action.type : null;
};
const toggleButton = (tabName) => {
    activeTab.value = tabName;
    fetchData();
    check.value = false;
    checked.value.length=0;
};



const selectedProducts = computed(() => {
    return dataList.value.filter(item => checked.value.includes(item.id));
});

const computedTotalPrice = computed(() => {
    let total = 0;
    selectedProducts.value.forEach(item => {
        total += parseFloat(item.price) * item.number;
    });
    return total;
    
});
window.localStorage.setItem("computedTotalPrice", JSON.stringify(computedTotalPrice));

const changeStep = (value, item) => {
    const index = dataList.value.findIndex(it => it.id === item.id);
    if (index !== -1) {
        dataList.value[index].number = value; // 更新商品数量
    }
};

const toggleAllCheckboxes = () => {
    const allIds = dataList.value.map(item => item.id);
    checked.value = check.value ? allIds : [];
};

const changeCheckboxGroup = (checkedIds) => {
    checked.value = checkedIds;
    check.value = checkedIds.length === dataList.value.length;
};

const onSubmit = () => {
    if (checked.value.length === 0) {
        Toast('请选择要结算的商品');
        return;
    }
    const dataToSend = formatSelectedProductsData();
    console.log('提交结算的数据:', dataToSend);
    handlePreOrder(dataToSend)
    // Toast(`您的总价为：${computedTotalPrice.value}`);
};

const handlePreOrder = (str) => {
    let formData = new FormData();
    formData.append("data", str);
    preOrder(formData).then(res => {
        if (res.code == 1) {
            // console.log(res.data);
            router.push({
                path: "/home/qrdd/" + res.data,
                // name: "qrdd",
                state: { id: res.data }
            });
        } else {
            Toast(res.msg);
        }
    });
    formData = new FormData();
};

const fetchData = () => {
    let formData = new FormData();
    formData.append("type", findReamrkByName(tabs.value, activeTab.value))
    ProductcartLists(formData).then(res => {
        if (res.code == 1) {
            dataList.value = res.data.data;
            nextTick(() => {
                totalPrice.value = computedTotalPrice.value;
            });
        } else {
            Toast(res.msg);
        }
    });
};

onMounted(() => {
    fetchData();
});

const deleteButton = (id) => {
    const index = dataList.value.findIndex(item => item.id === id);
    if (index !== -1) {
        const formData = new FormData();
        formData.append("ids", id);
        dataList.value.splice(index, 1); // 从dataList中移除商品
        checked.value = checked.value.filter(cid => cid !== id); // 从checked中移除商品id
        ProductcartDel(formData).then(res => {
            if (res.code == 1) {
                Toast(res.msg);
                fetchData();
            } else {
                Toast(res.msg);
            }
        });
    }
};

const getSelectedProductsData = () => {
    return checked.value.map(id => ({
        sku_id: dataList.value.find(item => item.id === id).sku_id,
        number: dataList.value.find(item => item.id === id).number
    }));
};

const formatSelectedProductsData = () => {
    const selectedData = getSelectedProductsData();
    return selectedData.map(item => `sku_id:${item.sku_id},number:${item.number}`).join('|');
};
</script>
<style scoped lang="less">
.shop {
    padding: 66px 15px;

    .top {
        h2 {
            font-weight: 400;
            font-size: 22px;
            color: #232323;
            text-align: left;
        }

        .btn {
            display: flex;
            justify-content: flex-start;

            .van-button {
                font-size: 12px;
                color: #666666;
                width: 80px;
                height: 24px;
                background: #F6F7F9;
                border-radius: 347px 347px 347px 347px;
                margin-right: 20px;

                // &:nth-child(2) {
                //     background: #F6F7F9;
                //     border-radius: 80px 80px 80px 80px;
                // }
            }

            .van-button.active {
                color: #FFFFFF;
                background: linear-gradient(143deg, #0A84FF 0%, #0A7EF3 100%);
            }
        }
    }

    .middle {
        :deep(.van-checkbox__label) {
            width: 100%;
        }

        .van-card {
            margin-top: 25px;

            :deep(.van-card__content) {
                display: flex;
                // justify-content: flex-start;
                align-items: flex-start;
            }

            :deep(.van-card__title) {
                margin-top: 5px;
            }

            :deep(.van-image__img) {
                height: 80px;
                margin-top: 5px;
            }

            :deep(.van-ellipsis) {
                margin-top: 10px;
            }

            :deep(.van-card__title) {
                text-align: left;
            }

            :deep(.van-card__desc) {
                text-align: left;
            }

            :deep(.van-card__num) {
                text-align: right;
            }

            :deep(.van-card__thumb) {
                width: 90px;
                height: 76px;
                border-radius: 8px 8px 8px 8px;
            }
            :deep(.van-card__bottom) {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: -20px;
            }
            :deep(.van-card__price) {
                color: #E1222A;
                font-size: 14px;
            }
        }

        .van-stepper {

            :deep(.van-stepper__plus) {
                background-color: #0A82FB;
            }

            :deep(.van-stepper__minus) {
                border-color: #0A84FF;
                color: #0A84FF;
            }
        }
    }

    .btm {
        .van-submit-bar {
            bottom: 66px;
        }
    }
}
</style>